from django.shortcuts import render
from django.http import HttpResponse
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
from io import BytesIO
from django.shortcuts import redirect
from django.urls import reverse
from utils.encrypt import md5
from myadmin.models import User, Shop, Category, Product


# Create your views here.


def index(request):
    """ 首页 """
    return redirect(reverse(web_index))


def web_index(request):
    """ 首页 """
    # 尝试从session中获取名字为cart_list的购物车信息，没有返回{}
    cart_list = request.session.get('cart_list', {})
    total_money = 0  # 初始化总金额

    for vo in cart_list.values():
        total_money += int(vo['num']) * int(vo['price'])

    request.session['total_money'] = total_money

    # items()  字典不支持循环
    context = {'category_list': request.session.get('category_list', {}).items()}
    # print(context)
    return render(request, 'web/index.html', context)


def login(request):
    """ 登录 """
    shop_list = Shop.objects.filter(status=1)
    # for i in shop_list:
    #     print(i.name)
    context = {'shop_list': shop_list}
    return render(request, 'web/login.html', context)


def dologin(request):
    """ 执行登录 """
    try:
        # 校验是否选择了店铺
        shop_id = request.POST['shop_id']
        if shop_id == '0':
            return redirect(reverse('web_login') + "?errinfo=1")

        # 验证码校验
        code = request.POST['code']
        if code != request.session['verifycode']:
            return redirect(reverse('web_login') + "?errinfo=2")

        username = request.POST['username']
        user = User.objects.get(username=username)
        # 判断是否是管理员或者是否正常
        if user.status == 6 or user.status == 1:
            # 判断密码是否相同
            password = request.POST['password'] + str(user.password_salt)
            # 拿到密码加盐后再加密
            passwords = md5(password)
            # print(passwords)
            # 判断密码是否正确
            if passwords != user.password_hash:
                return redirect(reverse('web_login') + "?errinfo=5")
            else:
                # 成功后写入session中 并重定向到后台首页
                request.session['webuser'] = user.toDict()  # 对象转字典

                # 登录成功获取当前店铺信息
                shopob = Shop.objects.get(id=shop_id)
                request.session['shopinfo'] = shopob.toDict()

                # 获取当前店铺的菜品类别和菜品信息
                clist = Category.objects.filter(shop_id=shopob.id, status=1)
                category_list = dict()  # 存放菜品类别【内含有菜品信息
                product_list = dict()  # 存放菜品信息
                for item in clist:  # 遍历菜品类别
                    c = {'id': item.id, 'name': item.name, 'pids': []}
                    plist = Product.objects.filter(category_id=item.id, status=1)
                    for p in plist:  # 遍历当前类别小的菜品信息
                        c['pids'].append(p.toDict())
                        product_list[p.id] = p.toDict()
                    category_list[item.id] = c

                # 存到session中
                request.session['category_list'] = category_list
                request.session['product_list'] = product_list
                # 重定向
                return redirect(reverse('web_index'))
        else:
            return redirect(reverse('web_login') + "?errinfo=4")
    except Exception as arr:
        print(arr)
        return redirect(reverse('web_login') + "?errinfo=3")


def logout(request):
    """ 退出 """
    del request.session['webuser']

    # 清空购物车
    request.session['cart_list'] = {}
    return redirect(reverse('web_login'))


def verify(request, width=120, height=30, char_length=5, font_file='static/FZSTK.ttf', font_size=28):
    """ 验证码 """
    code = ''

    img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
    draw = ImageDraw.Draw(img, mode='RGB')

    def rndChar():
        """
        生成随机字母
        :return:
        """
        return chr(random.randint(65, 90))

    def rndColor():
        """
        生成随机颜色
        :return:
        """
        return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))

    # 写文字
    font = ImageFont.truetype(font_file, font_size)
    for i in range(char_length):
        char = rndChar()
        # code.append(char)
        code = code + char
        h = random.randint(0, 4)
        draw.text([i * width / char_length, h], char, font=font, fill=rndColor())

    print(code)
    # 写到session中
    request.session['verifycode'] = code
    # 写干扰点
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())

    # 写干扰圆圈
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())

    # 画干扰线
    for i in range(5):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)

        draw.line((x1, y1, x2, y2), fill=rndColor())

    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    # 内存文件操作
    stream = BytesIO()
    # 将图片保存到内存中
    img.save(stream, 'png')
    # 返回给浏览器
    return HttpResponse(stream.getvalue(), 'image/png')
